﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Tower :MonoBehaviour, IRuseable
{
    protected float overLap = 0;
    protected Monster target;
    protected float times=1f;
    protected float ctimes ;
    protected float lastTime = 0;
    protected Transform bulletPos;
    protected Animation anim;
    protected string attacketPos;
    public virtual void Onspawn()
    {
        lastTime = Time.fixedTime;
        bulletPos = transform.Find("CATRigPelvis");
        anim = GetComponent<Animation>();
        anim["Idle"].layer = -1;
        StopAllCoroutines();
        StartCoroutine(LockTarget());

    }

    public virtual void OnUnspawn()
    {

    }
    
    IEnumerator LockTarget()
    {
        while(true)
        {
            if (target != null && target.gameObject.activeSelf && Vector3.Distance(transform.position, target.transform.position) < overLap)
            {
                transform.LookAt(target.transform.position);
                AnimationState s = anim.PlayQueued(attacketPos, QueueMode.PlayNow);
                AudioManage.SoundPlay("attack");
                Invoke("Attacked", s.length);
            }
            else
            {
                target = null;
                if (Spawner.monsters != null)
                {
                    foreach (var t in Spawner.monsters)
                    {
                        if (Vector3.Distance(transform.position, t.transform.position) < overLap)
                        {
                            target = t.GetComponent<Monster>();
                            break;
                        }
                    }
                    if (target != null)
                    {
                        transform.LookAt(target.transform.position);
                        AnimationState s = anim.PlayQueued(attacketPos, QueueMode.PlayNow);
                        AudioManage.SoundPlay("attack");
                        Invoke("Attacked", s.length);
                    }
                }
            }
            yield return new WaitForSeconds(1);
        }        
    }
    public virtual void Attacked()
    {
    }
}
